package com.pansoft.hd;


import com.pansoft.hd.model.BaseHDWallet;
import com.pansoft.hd.model.BtcHdWallet;
import com.pansoft.hd.model.EthHdWallet;
import com.pansoft.hd.model.HDException;
import com.pansoft.openplanet.account.model.BtcBean;
import com.pansoft.openplanet.account.model.EthBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;

import java.math.BigDecimal;
import java.util.List;

/**
 * HD钱包管理
 *
 * @author yqs
 */
public class HDAccountManager {
    private static final String TAG = "HDAccountManager";
    private HDWalletGenerator hdWalletGenerator;

//    /**
//     * 获取存储HD钱包的目录
//     *
//     * @return
//     */
//    public static String getHDKeyStoreDir() {
//        String dir = AppContext.getInstance().getFilesDir().getAbsolutePath()
//                + File.separator
//                + "/hdkeystore/" + EnvironmentVariable.getUserName();
//
////     String   dir="C:\\Users\\yqs97\\Desktop\\Web3j-demo-master\\新建文件夹";
////        FileUtils.createOrExistsDir(dir);
//        return dir;
//    }


    public HDAccountManager() {
        this.hdWalletGenerator = new HDWalletGenerator();
    }


    /**
     * 创建随机的12位助记词
     *
     * @return
     */
    public List<String> createRandomMnemonic() {
        List<String> mnemonicList = HDWalletUtil.generateMnemonic();
        return mnemonicList;
    }


    /**
     * 创建HD钱包（同时创建 eth btc）
     *
     * @param password 钱包密码
     * @param name     钱包名称
     * @return
     */
//    public HDAccount createHDAccount(String password, String name, String keystoreDir) {
//        List<String> mnemonicList = createRandomMnemonic();
//
//        String mnemonic = Joiner.on(" ").join(mnemonicList);
//        IHDWallet ethWallet = createETHWallet(mnemonicList, password, keystoreDir);
//        IHDWallet btcWallet = createHDBtcWallet(mnemonicList, password, keystoreDir);
//
//        HDAccount hdAccount = new HDAccount();
//        AESSecretUtil aesSecretUtil = new AESSecretUtil(password);
//        String encryptMnemonic = aesSecretUtil.encrypt(mnemonic);
//        hdAccount.setEncryptMnemonic(encryptMnemonic);
//        hdAccount.setMnemonic(mnemonic);
//        hdAccount.getHdWalletList().add(ethWallet);
//        hdAccount.getHdWalletList().add(btcWallet);
//        return hdAccount;
//    }

    /**
     * 使用助记词创建 HD btc 钱包
     *
     * @param mnemonicList 助记词
     * @param password     密码
     * @param keystoreDir  keystore文件目录
     * @return
     */
//    public IHDWallet createHDBtcWallet(List<String> mnemonicList, String password, String keystoreDir) {
//        IHDWallet btcWallet = hdWalletGenerator.generateWallet(mnemonicList, password,
//                BtcNetParamUtil.getBtcBipPath(), IPAssetsConstant.ChainEnum.BTC, HDWalletUtil.getNetworkParameters(), keystoreDir);
//        return btcWallet;
//    }

    /**
     * 使用助记词创建 HD eth 钱包
     *
     * @param mnemonicList 助记词
     * @param password     密码
     * @param keystoreDir  keystore文件目录
     * @return
     */
//    public IHDWallet createETHWallet(List<String> mnemonicList, String password, String keystoreDir) {
//        IHDWallet ethWallet = hdWalletGenerator.generateWallet(mnemonicList, password,
//                BIP44Util.ETHEREUM_PATH, IPAssetsConstant.ChainEnum.ETH, HDWalletUtil.getNetworkParameters(), keystoreDir);
//        return ethWallet;
//    }


    /**
     * 使用助记词创建 HD eth 钱包
     *
     * @param mnemonicList 助记词
     * @param password     密码
     * @param keystoreDir  keystore文件目录
     * @return
     */
//    public IHDWallet createEteWallet(List<String> mnemonicList, String password, String keystoreDir) {
//        EthHdWallet ethWallet = (EthHdWallet) hdWalletGenerator.generateWallet(mnemonicList, password,
//                BIP44Util.ETE_PATH, IPAssetsConstant.ChainEnum.ETE, HDWalletUtil.getNetworkParameters(), keystoreDir);
//        return ethWallet;
//    }

//    /**
//     * 使用助记词创建 HD 钱包
//     *
//     * @param mnemonicList 助记词
//     * @param password     密码
//     * @param keystoreDir  keystore文件目录
//     * @param bipPath      bip路径
//     * @return
//     */
//    public IHDWallet createWallet(List<String> mnemonicList, String password, String keystoreDir, String bipPath, IPAssetsConstant.ChainEnum chainEnum) {
//        IHDWallet ihdWallet = hdWalletGenerator.generateWallet(mnemonicList, password,
//                bipPath, chainEnum, HDWalletUtil.getNetworkParameters(), keystoreDir);
//        return ihdWallet;
//    }

    /**
     * 使用助记词创建 HD 钱包
     *
     * @param mnemonicList 助记词
     * @param password     密码
     * @param keystoreDir  keystore文件目录
     * @param chainEnum    链信息
     * @return
     */
    public BaseHDWallet createWallet(List<String> mnemonicList, String password, String keystoreDir, IPAssetsConstant.ChainEnum chainEnum) {
        String bipPath = null;
        if (chainEnum == IPAssetsConstant.ChainEnum.ETH) {
            bipPath = BIP44Util.ETHEREUM_PATH;
        } else if (chainEnum == IPAssetsConstant.ChainEnum.ETE) {
            bipPath = BIP44Util.ETE_PATH;
        } else if (chainEnum == IPAssetsConstant.ChainEnum.BTC) {
            bipPath = BIP44Util.BITCOIN_MAINNET_PATH;
        }
        if (bipPath == null) {
            throw new HDException("bipPath cannot be null!!!!");
        }

        BaseHDWallet ihdWallet = hdWalletGenerator.generateWallet(mnemonicList, password,
                bipPath, chainEnum, HDWalletUtil.getNetworkParameters(), keystoreDir);
        return ihdWallet;
    }

    /**
     * 转换IHDWallet
     *
     * @param ihdWallet
     * @return
     */
    public EthBean convertHDWallet2ETHBean(BaseHDWallet ihdWallet) {
        if (ihdWallet instanceof EthHdWallet) {
            EthHdWallet ethHDWallet = (EthHdWallet) ihdWallet;
            EthBean ethBean = new EthBean.Builder()
                    .ethAddress(ethHDWallet.getAddress())
                    .ecKeyPair(ethHDWallet.getEcKeyPair())
                    .keyStoreFilePath(ethHDWallet.getFilePath())
                    .type(1)
                    .build();
            return ethBean;
        }
        return null;
    }


    /**
     * 转换IHDWallet
     *
     * @param ihdWallet
     * @return
     */
    public BtcBean convertHDWallet2BTCBean(BaseHDWallet ihdWallet, List<String> mnemonicList) {
        if (ihdWallet instanceof BtcHdWallet) {
            BtcHdWallet btcHdWallet = (BtcHdWallet) ihdWallet;
            BtcBean btcBean = new BtcBean.Builder()
                    .btcAddress(btcHdWallet.getAddress())
                    .btcPrivKey(btcHdWallet.getPrivateKey())
                    .mnemonic(HDWalletUtil.mnemonic2String(mnemonicList))
                    .btcPubKey(btcHdWallet.getPublicKey())
                    .build();
            btcBean.setHdWallet(true);
            btcBean.setHdBtcXpub(btcHdWallet.getXpub());
            //默认只有第一个子地址，path"/0/1", index "1"
            btcBean.setHdBtcCurrentChildAddress(btcHdWallet.getBtcChildAddresses().get(0).getAddress());
            btcBean.setHdBtcMaxChildIndex("1");
            return btcBean;
        }
        return null;
    }

    public static void main(String[] args) {
        HDAccountManager hdAccountManager = new HDAccountManager();

//        IHDWallet ihdWallet = hdAccountManager.createWallet(HDWalletUtil.mnemonicString2List("shove stand collect skull stone market people useful bright junior sting decline"), "",
//                "C:\\Users\\yqs97\\Desktop", IPAssetsConstant.ChainEnum.ETE);

//        IHDWallet ihdWallet = hdAccountManager.createWallet(HDWalletUtil.mnemonicString2List("palace print horror bridge zone chuckle that drip image scene country spirit"), "",
////        IHDWallet ihdWallet = hdAccountManager.createWallet(HDWalletUtil.mnemonicString2List("tourist minute will hello avoid fashion interest sausage advice radio icon grain"), "",
//                "C:\\Users\\yqs97\\Desktop", IPAssetsConstant.ChainEnum.ETH);
//        EthHdWallet ethHDWallet = (EthHdWallet) ihdWallet;
//        System.out.println(ethHDWallet.getAddress());
        System.out.println(new BigDecimal(".23").toPlainString());
        System.out.println(new BigDecimal("0110").toPlainString());
    }
}